package com.cjj.thread_safe;

class ThreadTrain2 implements Runnable {

    // 车票总数
    private int count = 100;

    private Object object = new Object();

    @Override
    public void run() {
        /*while (count > 0) {
            show();
        }*/
        while (count > 0){
            synchronized (this){
                if (count > 0) {
                    try {
                        Thread.sleep(40);
                    } catch (Exception e) {

                    }
                    System.out.println(Thread.currentThread().getName() + "出售第" + (100 - count + 1) + "张票");
                    count--;
                }
            }
        }
    }

    public synchronized void show() {
        if (count > 0) {
            try {
                Thread.sleep(40);
            } catch (Exception e) {

            }
            System.out.println(Thread.currentThread().getName() + "出售第" + (100 - count + 1) + "张票");
            count--;
        }
    }
}

/**
 * 使用同步函数(同步方法)
 *
 * @ClassName Thread_01
 * @Date 2021/07/17 11:23:43
 * @Created by ccc-j
 * @email ccc-ju@outlook.com
 */
public class Thread_02 {

    public static void main(String[] args) {
        // 创建两个线程, 线程类一定要是一个实例
        ThreadTrain2 threadTrain = new ThreadTrain2();
        Thread thread_1 = new Thread(threadTrain);
        Thread thread_2 = new Thread(threadTrain);
        thread_1.start();
        thread_2.start();
    }

}
